/*
 * CDataStore.h
 *
 *  Created on: 2017年3月5日
 *      Author: chuanjiang.zh
 */

#ifndef CDATASTORE_H_
#define CDATASTORE_H_

#include "DataStore.h"
#include "sqlite3.h"
#include "TCriticalSection.h"


class CDataStore: public DataStore
{
public:
	CDataStore();
	virtual ~CDataStore();

	virtual bool open(const std::string& path);

    virtual void close();

    virtual bool isOpen();

	virtual bool addRecord(av::MRecord& record);

	virtual bool updateRecord(const av::MRecord& record);

	virtual bool removeRecord(int id);

	virtual int searchRecord(const av::MRecordQuery& query, int offset, av::MRecord* records, int size);

	virtual int countRecord(const av::MRecordQuery& query);

	virtual bool removeRecords(const char* device, time_t fromTime, time_t toTime, int events);

	virtual bool getRecord(int id, av::MRecord& record);

	virtual bool findRecord(const char* filename, av::MRecord& record);

	virtual bool addEvent(av::AlarmEvent& event);

	virtual bool removeEvent(int id);

	virtual int searchEvent(const char* device, time_t fromTime, time_t toTime, int events,
			av::AlarmEvent* alarmEvents, int size);

	virtual bool removeEvents(const char* device, time_t fromTime, time_t toTime, int events);

	virtual bool getEvent(int id, av::AlarmEvent& event);

	virtual int listRecord(const char* device, int offset, av::MRecord* records, int size);

protected:
    bool execute(const std::string& sql);

    int queryInt(const std::string& sql, int defValue=0);

    bool insert(const std::string& sql, int& autoId);

    bool insert(const std::string& sql, int64_t& autoId);

    bool queryRecord(const std::string& sql, av::MRecord& record);
    bool queryEvent(const std::string& sql, av::AlarmEvent& event);

    int queryRecords(const std::string& sql, av::MRecord* records, int size);
    int queryEvents(const std::string& sql, av::AlarmEvent* events, int size);

    void createTables();

    void toRecord(sqlite3_stmt *stmt, av::MRecord& record);
    void toEvent(sqlite3_stmt *stmt, av::AlarmEvent& event);

protected:
    sqlite3*    m_sqlite;
	comn::CriticalSection	m_cs;


};

#endif /* CDATASTORE_H_ */
